package com.zhengtoudai.ui.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import com.zhengtoudai.R;
import com.zhengtoudai.base.App;
import com.zhengtoudai.base.BaseActivity;
import com.zhengtoudai.database.DBManager;
import com.zhengtoudai.database.UserInfo;
import com.zhengtoudai.global.Config;
import com.zhengtoudai.http.HttpUtil;
import com.zhengtoudai.injector.component.DaggerActivityComponent;
import com.zhengtoudai.ui.bean.Login;
import com.zhengtoudai.ui.bean.Result;
import com.zhengtoudai.ui.presenter.LoginPresenterImpl;
import com.zhengtoudai.ui.view.LoginView;
import com.zhengtoudai.util.AbToastUtil;
import com.zhengtoudai.util.Tool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 登录
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class LoginActivity extends BaseActivity implements LoginView {
    @Bind(R.id.tv_mobile_phone)
    AutoCompleteTextView mTvMobilePhone;
    @Bind(R.id.edt_password)
    EditText mEdtPassword;

    @Inject
    DBManager mDBManager;

    @Inject
    LoginPresenterImpl mPresenter;

    //跳转注册界面请求码
    private final int REGISTER_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    }

    @Override
    protected void initTitle() {
        titleUtil.setTitle("登录");

    }

    @Override
    protected void initView() {
       DaggerActivityComponent.builder().appComponent(App.mApp.getAppComponent())
                .activityModule(getActivityModule())
                .build()
                .inject(this);
        mPresenter.attachView(this);
        mTvMobilePhone.setAdapter(new UserAdapter(mDBManager.queryAll(), context));
        mTvMobilePhone.setThreshold(1);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDBManager.closeDB();
        mPresenter.detachView();
    }

    private void attemptLogin() {

        // Reset errors.
        mTvMobilePhone.setError(null);
        mEdtPassword.setError(null);


        String phone = mTvMobilePhone.getText().toString();
        String password = mEdtPassword.getText().toString();
        //输入的手机密码是否正确，为false才能去执行登录操作
        boolean cancel = false;

        View focusView = null;

        if (TextUtils.isEmpty(password) || password.length() < 6) {
            mEdtPassword.setError(getString(R.string.error_invalid_password));
            focusView = mEdtPassword;
            cancel = true;
        }

        if (TextUtils.isEmpty(phone)) {
            mTvMobilePhone.setError(getString(R.string.error_field_required));
            focusView = mTvMobilePhone;
            cancel = true;
        } else if (phone.length() != 11) {
            mTvMobilePhone.setError(getString(R.string.error_invalid_email));
            focusView = mTvMobilePhone;
            cancel = true;
        }
        if (cancel) {
            //获取光标
            focusView.requestFocus();
        } else {
            //格式正确，调用登录接口
            mPresenter.login(phone,password);
        }
    }

    @OnClick({R.id.btn_login, R.id.tv_forget_password, R.id.btn_register})
    public void onClick(View view) {
        if (Tool.isFastDoubleClick()) return;

        switch (view.getId()) {
            case R.id.btn_login:
                attemptLogin();
                break;
            case R.id.tv_forget_password:
                startActivity(ForgetPasswordActivity.class);
                break;
            case R.id.btn_register:
                startActivityForResult(REGISTER_REQUEST_CODE,RegisterActivity.class);
                //startActivity(RegisterActivity.class);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REGISTER_REQUEST_CODE&&resultCode==RESULT_OK){
            if (data!=null){
                String mobile=data.getStringExtra("mobile");
                String password=data.getStringExtra("password");
                if (!TextUtils.isEmpty(mobile)&&!TextUtils.isEmpty(password)){
                    mPresenter.login(mobile,password);
                }
            }
        }
    }

    @Override
    public void showDialog() {
        showProgressDialog("正在登陆中");
    }



    @Override
    public void onFailure(Throwable e) {
        HttpUtil.disposeOnFailure(context,e);
    }

    @Override
    public void loginResult(Result<Login> login) {
        if (login.getCode() == Config.SUCCESSFUL_CODE) {
            Map<String, String> userInfo = new HashMap<>();
            userInfo.put("JSESSIONID", login.getResult().getJSESSIONID());
            userInfo.put("token", login.getResult().getToken());
            userInfo.put("isDepositUser", login.getResult().getIsDepositUser());
            App.mApp.getSession().set(userInfo);

            Log.e("TAG","打印保存的数据=="+App.mApp.getSession().get("JSESSIONID"));

            UserInfo info = new UserInfo(mTvMobilePhone.getText().toString(), mEdtPassword.getText().toString());
            mDBManager.add(info);

            finish();
        }
        AbToastUtil.showToast(context, login.getMessage());
    }

    @Override
    public void dismissDialog() {
        dismissProgressDialog();
    }


    public class UserAdapter extends BaseAdapter implements Filterable {
        private ArrayFilter mFilter;
        private Context mContext;
        private ArrayList<UserInfo> mUnfilteredData;
        private List<UserInfo> mList;

        public UserAdapter(List<UserInfo> mList, Context context) {
            this.mList = mList;
            mContext = context;
        }

        @Override
        public int getCount() {
            return mList == null ? 0 : mList.size();
        }


        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item_user_login, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.mTvPhone.setText(mList.get(position).getPhone());
            holder.mTvPhone.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mTvMobilePhone.setText(mList.get(position).getPhone());
                    mEdtPassword.setText(mList.get(position).getPassword());
                    mEdtPassword.requestFocus();
                    mEdtPassword.setSelection(mList.get(position).getPassword().length());
                    mTvMobilePhone.dismissDropDown();
                    Tool.hideInputMethod(LoginActivity.this);
                }
            });
            holder.mTvCancel.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDBManager.deleteUser(mList.get(position).getPhone());
                    mList.remove(position);
                    mUnfilteredData.remove(position);
                    notifyDataSetChanged();
                }
            });
            return convertView;
        }

        @Override
        public Object getItem(int position) {
            return mList == null ? 0 : mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Filter getFilter() {
            if (mFilter == null) {
                mFilter = new ArrayFilter();
            }
            return mFilter;
        }

        public class ViewHolder {

            TextView mTvPhone;

            TextView mTvCancel;

            ViewHolder(View view) {
                mTvPhone = (TextView) view.findViewById(R.id.tv_phone);
                mTvCancel = (TextView) view.findViewById(R.id.tv_cancel);
            }
        }

        private class ArrayFilter extends Filter {

            @Override
            protected FilterResults performFiltering(CharSequence prefix) {
                FilterResults results = new FilterResults();

                if (mUnfilteredData == null) {
                    mUnfilteredData = new ArrayList<>(mList);
                }

                if (prefix == null || prefix.length() == 0) {
                    ArrayList<UserInfo> list = mUnfilteredData;
                    results.values = list;
                    results.count = list.size();
                } else {
                    String prefixString = prefix.toString().toLowerCase();

                    ArrayList<UserInfo> unfilteredValues = mUnfilteredData;
                    int count = unfilteredValues.size();

                    ArrayList<UserInfo> newValues = new ArrayList<UserInfo>(count);

                    for (int i = 0; i < count; i++) {
                        UserInfo pc = unfilteredValues.get(i);
                        if (pc != null) {

                            if (pc.getPhone() != null && pc.getPhone().startsWith(prefixString)) {

                                newValues.add(pc);
                            } else if (pc.getPassword() != null && pc.getPassword().startsWith(prefixString)) {

                                newValues.add(pc);
                            }
                        }
                    }

                    results.values = newValues;
                    results.count = newValues.size();
                }

                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                //noinspection unchecked
                mList = (List<UserInfo>) results.values;
                if (results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }

        }
    }
}

